package cn.kent.simple;

/**
 * 69. x 的平方根
 */
public class MySqrt {
    public static void main(String[] args) {
        int n = 2147395599;
        System.out.println(Integer.MAX_VALUE);
        System.out.println(mySqrt(n));
        System.out.println(mySqrt2(n));
        System.out.println(mySqrt3(n));
        System.out.println(mySqrt4(n));
    }

    /**
     * 一般不让用这个函数直接求解
     */
    public static int mySqrt(int x) {
        return (int) Math.sqrt(x);
    }

    /**
     * 二分查找
     * k平方<=x
     * 1ms
     */
    public static int mySqrt2(int x) {
        if (x == 0) {
            return x;
        }
        int left = 0;
        int right = x;
        int res = 0;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if ((long) mid * mid <= x) {
                left = mid + 1;
                res = mid;
            } else {
                right = mid - 1;
            }
        }
        return res;
    }

    /**
     * 袖珍计算器法
     * 用指数函数和对数函数代替平方根函数
     */
    public static int mySqrt3(int x) {
        if (x == 0) {
            return 0;
        }
        int ans = (int) Math.exp(0.5 * Math.log(x));
        return (long) (ans + 1) * (ans + 1) <= x ? ans + 1 : ans;
    }


    /**
     * 牛顿迭代
     */
    public static int mySqrt4(int x) {
        if (x == 0) {
            return 0;
        }

        double C = x, x0 = x;
        while (true) {
            double xi = 0.5 * (x0 + C / x0);
            System.out.println("xi = " + xi);
            if (Math.abs(x0 - xi) < 1e-7) {
                break;
            }
            x0 = xi;
        }
        return (int) x0;
    }

}
